const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');

const { config: loadEnvConfig } = dotenv;

// 目录路径
const ROOT_PATH = path.join(__dirname, '../');
const ENV_CONFIG_PATH = path.join(ROOT_PATH, '.env');

loadEnvConfig({ path: ENV_CONFIG_PATH });

let TLS = false;
const PROJ_NAME = process.env.PROJ_NAME;
const SUBDOMAIN = process.env.SUBDOMAIN;
const BACKEND_SERVER = process.env.BACKEND_SERVER;
const SSH_SERVER_HOST = process.env.SSH_SERVER_HOST;

try {
  TLS = JSON.parse(process.env.TLS);
} catch {
  TLS = false;
}

const proxyNginxConf = !!BACKEND_SERVER
  ? `
    location /api/ {
        rewrite   /api/(.*)   /$1   break;
        proxy_pass    ${BACKEND_SERVER};
    }
`
  : '';

function main() {
  if (!SUBDOMAIN && !PROJ_NAME) {
    console.log('SUBDOMAIN and PROJ_NAME are undefined, 无法分配子域名, 请在 .env 中进行配置！');
    process.exitCode = 1;
    return;
  }
  const router = (SUBDOMAIN || PROJ_NAME).replaceAll(' ', '_');
  if (!SSH_SERVER_HOST) {
    console.log('SSH_SERVER_HOST is undefined, 无法配置域名以及上传服务器');
    process.exitCode = 1;
    return;
  }

  fs.writeFileSync(
    'docker-compose.yaml',
    `
version: "3"
services:
  frontend:
    image: nginx:alpine
    labels:
      # 配置自定义域名
      - "traefik.http.routers.${router}.rule=Host(\`${router}.${SSH_SERVER_HOST}\`)"
      # 是否开启 https, 这里配置开启
      - traefik.http.routers.${router}.tls=${TLS ? 'true' : 'false'}
      - traefik.http.routers.${router}.tls.certresolver=le
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf
      - ./dist:/usr/share/nginx/html

networks:
  default:
    external:
      name: traefik_default

`,
    'utf-8',
  );
  console.log('Generate docker-compose.yaml Success!');

  fs.writeFileSync(
    'nginx.conf',
    `
server {
    listen      80;
    server_name localhost;

    root    /usr/share/nginx/html;
    index   index.html index.htm;

    location / {
        try_files   $uri $uri/ /index.html;

        gzip        on;
        # 非带 hash 的资源，需要配置 Cache-Control: no-cache，避免浏览器默认为强缓存
        expires     -1;
    }
    ${proxyNginxConf}
    location /assets {
        # 带 hash 的资源，需要配置长期缓存
        expires     1y;
    }
}
`,
    'utf-8',
  );
  console.log('Generate nginx.conf Success!');
}

main();
